package com.easygsp.web.servlet;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.ModelAndView;

/**
 * 池化了ModelAndView的分发器
 * @author JKnife
 *
 */
public class PooledModelAndViewDispatchServlet extends DispatcherServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5706379406634443416L;
	
	/**
	 * 最多 ModelAndView 数量
	 */
	private static final int MAX_MODELANDVIEW = 50;

	private static List<ModelAndView> modeAndViews = new ArrayList<ModelAndView>(
			MAX_MODELANDVIEW);

	static {
		for (int i = 0; i < MAX_MODELANDVIEW; i++) { // 缓存量为50
			modeAndViews.add(new ModelAndView());
		}
	}

	public void render(ModelAndView mv, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		super.render(mv, request, response);
		releaseModelAndView(mv);
	}

	// 回收ModelAndView
	private void releaseModelAndView(ModelAndView mv) {
		mv.clear();
		mv.getModelMap().clear();
		synchronized (modeAndViews) {
			modeAndViews.add(mv);
		}
	}

	// 取ModelAndView
	public static ModelAndView getModeAndView() {
		synchronized (modeAndViews) {
			if (modeAndViews.size() > 0)
				return modeAndViews.remove(0);
			else
				return new ModelAndView();
		}
	}

}
